#include "qsendfile.h"

#include <QFile>

QSendFile::QSendFile()
{
}

bool QSendFile::load(const QString &name)
{
    reset();
    QFile f(name);
    if(!f.open(QFile::ReadOnly))
    {
        return false;
    }

    QByteArray data=f.readAll();

    int pt=0;

    int len;
    QByteArray d;
    uint u;
    while(pt<data.size())
    {
        len=(data.size()-pt)>1000?1000:(data.size()-pt);
        d=data.mid(pt,len);
        u=0;
        for(int i=0;i<len;i++)
        {
            u+=((d.at(i))&0xff);
        }
        d.append((u>>24)&0xff);
        d.append((u>>16)&0xff);
        d.append((u>>8)&0xff);
        d.append(u&0xff);
        m_send_data.append(d);
        pt+=len;
    }

    m_send_point=-1;

    return true;
}

QByteArray QSendFile::get_send_data()
{
    if(m_send_point>=m_send_data.size())
    {
        return QByteArray();
    }
    return m_send_data.at(m_send_point);
}

void QSendFile::move_to_next()
{
    m_send_point++;
}

void QSendFile::reset()
{
    m_send_data.clear();
    m_send_point=-1;
    m_recv_data=QByteArray();
    m_save_name="";
}

void QSendFile::add_recv_data(const QByteArray &data)
{
    m_recv_data+=data;
}

void QSendFile::set_save_path(const QString &name)
{
    m_save_name=name;
}

bool QSendFile::save()
{
    QFile f(m_save_name);

    if(!f.open(QFile::ReadWrite))
    {
        return false;
    }
    f.resize(0);

    f.write(m_recv_data);
    f.close();

    return true;
}

int QSendFile::count()
{
    return m_send_data.size();
}
